﻿using System;

namespace PortableTPL
{
    public class CancellationToken
    {
        Action cancellationAction;
        bool isCancellationRequested;

        public bool IsCancellationRequested
        {
            get { return isCancellationRequested; }
        }

        public void Register(Action action)
        {
            cancellationAction = action;
        }

        public void ThrowIfCancellationRequested()
        {
            if (isCancellationRequested)
            {
                throw new OperationCanceledException(this);
            }
        }

        internal void Cancel()
        {
            isCancellationRequested = true;

            if (cancellationAction != null)
            {
                cancellationAction();
            }
        }
    }
}
